import React, { useEffect, useState } from 'react';
import { X, CloudUpload, CloudDownload, CloudCog, Loader2, Check, AlertCircle } from 'lucide-react';
import { uploadToCloud, downloadFromCloud } from '../services/storageService';

interface SettingsModalProps {
  isOpen: boolean;
  onClose: () => void;
}

type SyncStatus = 'idle' | 'loading' | 'success' | 'error';

export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose }) => {
  const [uploadStatus, setUploadStatus] = useState<SyncStatus>('idle');
  const [downloadStatus, setDownloadStatus] = useState<SyncStatus>('idle');

  useEffect(() => {
    if (isOpen) {
      setUploadStatus('idle');
      setDownloadStatus('idle');
    }
  }, [isOpen]);

  const handleUpload = async () => {
    if (uploadStatus === 'loading') return;
    setUploadStatus('loading');
    try {
      await uploadToCloud();
      setUploadStatus('success');
      setTimeout(() => setUploadStatus('idle'), 3000);
    } catch (e) {
      setUploadStatus('error');
      setTimeout(() => setUploadStatus('idle'), 3000);
    }
  };

  const handleDownload = async () => {
    if (downloadStatus === 'loading') return;
    setDownloadStatus('loading');
    try {
      await downloadFromCloud();
      setDownloadStatus('success');
      // Optional: Reload page or trigger data refresh if download actually updated localStorage
      setTimeout(() => {
        setDownloadStatus('idle');
        window.location.reload(); // Reload to reflect downloaded data
      }, 1000);
    } catch (e) {
      setDownloadStatus('error');
      setTimeout(() => setDownloadStatus('idle'), 3000);
    }
  };

  if (!isOpen) return null;

  const StatusIcon = ({ status }: { status: SyncStatus }) => {
    if (status === 'loading') return <Loader2 className="w-4 h-4 animate-spin" />;
    if (status === 'success') return <Check className="w-4 h-4" />;
    if (status === 'error') return <AlertCircle className="w-4 h-4" />;
    return null;
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg overflow-hidden animate-in fade-in zoom-in duration-200">
        <div className="px-6 py-4 border-b border-slate-100 flex justify-between items-center bg-slate-50">
          <h3 className="text-lg font-semibold text-slate-800 flex items-center gap-2">
            <CloudCog className="w-5 h-5 text-primary" />
            设置与云同步
          </h3>
          <button onClick={onClose} className="text-slate-400 hover:text-slate-600">
            <X className="w-5 h-5" />
          </button>
        </div>

        <div className="p-6 space-y-6">
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <h4 className="text-sm font-bold text-slate-800 uppercase tracking-wider">华为云 OBS 配置</h4>
            </div>

            <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3">
              <AlertCircle className="w-5 h-5 text-blue-600 shrink-0 mt-0.5" />
              <div className="text-sm text-blue-800">
                <p className="font-semibold mb-1">配置说明</p>
                <p>
                  华为云 OBS 的访问密钥（AK/SK）和桶配置
                  请确保在服务端 <code className="bg-blue-100 px-1 py-0.5 rounded">.env</code> 文件中正确配置了以下变量：
                </p>
                <ul className="list-disc list-inside mt-2 space-y-1 text-blue-700/80 font-mono text-xs">
                  <li>OBS_ACCESS_KEY_ID</li>
                  <li>OBS_SECRET_ACCESS_KEY</li>
                  <li>OBS_SERVER</li>
                  <li>OBS_BUCKET</li>
                </ul>
              </div>
            </div>
          </div>

          {/* Sync Actions */}
          <div className="pt-6 border-t border-slate-100">
            <h4 className="text-sm font-bold text-slate-800 uppercase tracking-wider mb-3">数据同步</h4>
            <div className="grid grid-cols-2 gap-3">
              {/* Download Button */}
              <button
                onClick={handleDownload}
                disabled={downloadStatus === 'loading'}
                className={`flex items-center justify-center gap-2 px-4 py-3 rounded-xl text-sm font-bold transition-all border ${downloadStatus === 'success'
                  ? 'bg-green-50 border-green-200 text-green-700'
                  : downloadStatus === 'error'
                    ? 'bg-red-50 border-red-200 text-red-700'
                    : 'bg-white border-slate-200 text-slate-600 hover:border-primary hover:text-primary hover:bg-indigo-50/50'
                  }`}
              >
                {downloadStatus === 'idle' && <CloudDownload className="w-4 h-4" />}
                <StatusIcon status={downloadStatus} />
                <span>
                  {downloadStatus === 'loading' ? '正在同步...' :
                    downloadStatus === 'success' ? '已同步到本地' :
                      downloadStatus === 'error' ? '同步失败' : '从云端同步到本地'}
                </span>
              </button>

              {/* Upload Button */}
              <button
                onClick={handleUpload}
                disabled={uploadStatus === 'loading'}
                className={`flex items-center justify-center gap-2 px-4 py-3 rounded-xl text-sm font-bold transition-all shadow-sm ${uploadStatus === 'success'
                  ? 'bg-green-600 text-white'
                  : uploadStatus === 'error'
                    ? 'bg-red-600 text-white'
                    : 'bg-primary text-white hover:bg-indigo-700'
                  }`}
              >
                {uploadStatus === 'idle' && <CloudUpload className="w-4 h-4" />}
                <StatusIcon status={uploadStatus} />
                <span>
                  {uploadStatus === 'loading' ? '正在上传...' :
                    uploadStatus === 'success' ? '上传成功' :
                      uploadStatus === 'error' ? '上传失败' : '将本地上传到云端'}
                </span>
              </button>
            </div>
            <p className="text-xs text-slate-400 mt-3 text-center">
              注意: "从云端同步" 将覆盖本地的历史记录，请谨慎操作。
            </p>
          </div>
        </div>
      </div>
    </div>
  );
};